// flyer/flyerSet/index.js
const app = getApp();
const pay = require('../../../utils/pay.js');
const utils = require('../../../utils/util.js')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    currentPage: 1,
    loadingMoreHidden: 1,
    tagindex: 1,
    currentSendFlyerid: 0,//当前开启的活动
    state: 0,//1开启，0关闭
    range: '',
    address: '',
    unitPrice: 0,//传单发放价格
    balance: 0,//余额
    predictCount: 0,//预计发放量
    totalMoney: 0,//已充值金额
    sendNumber: 0,//已发放人数
    showRuler: false,
    addFlyerDialog: false,
    flyerList: [],
    createUid: 0,
    flyerid: 0,
    flyerName: '',
    flyerCount: '',
    sendType: 0,//1 新客, 2 老客, 0 不限
    isNew: true,
    isOld: true,
    gradeType: 1,//0自己发放；1别人代发
    template: '',//活动背景图
    showTemplateImg: '',
    showFlyerCode: false,
    windowWidth: 314,
    platform: 'ios',
    showModel: false,
    merchantAddress: '',
    markers: [{
      iconPath: "/images/nav/map.png",
      id: 0,
      latitude: 0,
      longitude: 0,
      width: 18,
      height: 28
    }],
    longitude: 0,
    latitude: 0,
  },

  // 传单设置页面的方法start======
  // 商家出钱发传单说明
  toBossPay: function () {
    wx.navigateTo({
      url: '/pages/h5page/index?url=flyerRulesBossPay.html',
    })
  },
  // 帮人发传单赚钱说明
  toMerSendFlyer: function () {
    wx.navigateTo({
      url: '/pages/h5page/index?url=flyerRulesMerSend.html',
    })
  },
  // 充值弹窗
  showModel: function () {
    this.setData({
      showModel: !this.data.showModel
    })
  },
  //安卓手机现金充值
  submitAccountBalanceOrder: function () {
    if (!this.checkMoney(this.data.inputMoney)) {
      wx.showModal({
        title: '提示',
        content: '请输入50-9900整数',
        showCancel: false,
      })
      return
    }
    wx.showLoading({
      title: '充值中',
      mask: true
    })
    wx.request({
      url: app.globalData.host + '/api/Order/SubmitAccountBalanceOrder',
      data: {
        uid: app.globalData.userInfo.Uid,
        count: this.data.inputMoney / 50
      },
      method: 'POST',
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          pay.wxpay(app, res.data.Data, 1);
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  // 免单码弹窗
  showFlyerCode: function () {
    wx.request({
      url: app.globalData.host + '/api/Leaflet/GetGradeByUid?uid=' + app.globalData.userInfo.Uid + '&state=1',
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data && res.data.Data.QrCode) {
            wx.navigateTo({
              url: '../flyerCode/index?flyerCode=' + res.data.Data.QrCode,
            })
          } else {
            wx.showToast({
              title: '暂未生成免单码',
              icon: 'none',
              mask: true
            })
          }
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            confirmText: '去设置',
            success: function (res) {
              if (res.confirm) {
                let cardId = wx.getStorageSync('cardId')
                wx.navigateTo({
                  url: '/pages/weijieke/editorCard/index?staffid=' + cardId,
                })
              }
            }
          })
        }
      },
    })
  },

  // 生成免单码
  showFlyerCodeOld: function () {
    let that = this;
    let windowWidth = wx.getSystemInfoSync().windowWidth * 314 / 375;
    let canvsaHeight = windowWidth * 450 / 314;
    let qrCode = '';
    let flyerName = '';
    wx.request({
      url: app.globalData.host + '/api/Leaflet/GetGradeByUid?uid=' + app.globalData.userInfo.Uid + '&state=1',
      success: function (res) {
        if (res.data.Data) {
          if (res.data.Data.QrCode) {
            qrCode = utils.formatAvater(res.data.Data.QrCode, 'https://static.711688.net.cn/upload/share/');
          }
          flyerName = res.data.Data.Name;
          that.getAiCardInfo(qrCode, flyerName);
        }
      },
    })
    that.setData({
      showFlyerCode: !that.data.showFlyerCode,
      windowWidth: windowWidth,
      canvsaHeight: canvsaHeight
    })
  },
  // 生成单个传单码
  showFlyerCodeOne: function (e) {
    let flyerid = e.currentTarget.dataset.flyerid;
    let flyerName = e.currentTarget.dataset.flyername;
    let qrCode = e.currentTarget.dataset.qrcode;
    let that = this;
    let windowWidth = wx.getSystemInfoSync().windowWidth * 314 / 375;
    let canvsaHeight = windowWidth * 450 / 314;
    if (qrCode) {
      qrCode = utils.formatAvater(qrCode, 'https://static.711688.net.cn/upload/share/');
    }
    that.getAiCardInfo(qrCode, flyerName);
    // wx.request({
    //   url: app.globalData.host + '/api/Leaflet/GetGrade?id=' + flyerid,
    //   success: function (res) {
    //     if (res.data.Data) {
    //       if (res.data.Data.QrCode) {
    //         qrCode = utils.formatAvater(res.data.Data.QrCode, 'https://static.711688.net.cn/upload/share/');
    //       }
    //       flyerName = res.data.Data.Name;
    //       that.getAiCardInfo(qrCode, flyerName);
    //     }
    //   },
    // })
    that.data.codeFlyerid = flyerid;
    that.setData({
      showFlyerCode: !that.data.showFlyerCode,
      windowWidth: windowWidth,
      canvsaHeight: canvsaHeight
    })
  },

  // 免单码弹窗关闭
  closeFlyerCode: function () {
    this.setData({
      showFlyerCode: !this.data.showFlyerCode
    })
  },


  // 数字传单（传单活动列表）及其相关操作======
  // 查看当前活动发放量
  toFlyerSendList: function (e) {
    let flyerid = e.currentTarget.dataset.flyerid;
    let listType = e.currentTarget.dataset.listtype;
    let count = e.currentTarget.dataset.count;
    wx.navigateTo({
      url: '/merchant/share/holderList/index?gradeid=' + flyerid + '&listtype=' + listType + '&count=' + count,
    })
  },


  // 用户输入操作======
  //充值金额
  bindInputValue: function (e) {
    this.setData({
      inputMoney: parseFloat(e.detail.value)
    })
  },
  checkInput: function () {
    if (!this.checkMoney(this.data.inputMoney)) {
      wx.showModal({
        title: '提示',
        content: '请输入50-9900整数',
        showCancel: false,
      })
      return
    }
  },
  checkMoney: function (obj) {
    if (!obj) {
      return false;
    } else {
      return typeof obj === 'number' && obj % 50 === 0;//是整数，则返回true，否则返回false
    }
  },
  // 传单礼包数量
  bindFlayerCount: function (e) {
    this.setData({
      flyerCount: e.detail.value
    })
  },

  //充值（old）
  submitAccountBalanceOrder22: function () {
    if (!this.checkMoney(this.data.inputMoney)) {
      wx.showModal({
        title: '提示',
        content: '请输入50-9900整数',
        showCancel: false,
      })
      return
    }
    wx.showLoading({
      title: '充值中',
      mask: true
    })
    wx.request({
      url: app.globalData.host + '/api/Order/SubmitStaffOrder',
      data: {
        uid: app.globalData.userInfo.Uid,
        money: this.data.inputMoney,
        count: 1,
        orderType: 4
      },
      method: 'POST',
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          pay.wxcashpay(app, res.data.Data, '/merchant/flyer/flyerSet/index')
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  getAiCardInfo: function (qrcode, name) {
    let that = this;
    let userid = app.globalData.userInfo.Uid;
    wx.request({
      url: app.globalData.host + '/api/Staff/GetStaffIdByUid?Uid=' + userid,
      success: function (res) {
        let cardInfo = res.data.Data;
        that.getCanvasimg(qrcode, name, cardInfo);
      }
    })
  },

  // 免单码海报
  getCanvasimg: function (qrcode, name, cardInfo) {
    var that = this;
    let url = "https://static.711688.net.cn/upload/card/source/ua_1911051408175899450.png";
    wx.downloadFile({ //免单码背景图
      url: url,
      success: function (res) {
        let canvasimg = res.tempFilePath;
        that.beFlyerPost(qrcode, name, cardInfo, canvasimg);
      }
    })
  },

  beFlyerPost: function (qrcode, name, cardInfo, canvasimg) {
    var that = this;
    if (qrcode) {
      wx.downloadFile({
        url: qrcode,
        success: function (res) {
          if (res.statusCode === 200) {
            var codeSrc = res.tempFilePath;
            that.sharePoste(name, cardInfo, canvasimg, codeSrc);
          } else {
            wx.showToast({
              title: '二维码下载失败！',
              icon: 'none',
              duration: 2000,
              success: function () {
                var codeSrc = "";
                that.sharePoste(name, cardInfo, canvasimg, codeSrc);
              }
            })
          }
        }
      })
    } else {
      var codeSrc = "";
      that.sharePoste(name, cardInfo, canvasimg, codeSrc);
    }
  },
  sharePoste: function (name, cardInfo, canvasimg, codeSrc) {
    wx.showLoading({
      title: '生成中...',
      mask: true,
    })
    const ctx = wx.createCanvasContext('myCanvas');
    wx.createSelectorQuery().select('#canvas-container').boundingClientRect(function (rect) {
      var height = rect.height;
      var width = rect.width;

      // 绘制背景图
      ctx.drawImage(canvasimg, 0, 0, width, height);

      // 公司名
      if (cardInfo.Company) {
        ctx.setTextAlign('center');
        ctx.font = "18px sans-serif";
        ctx.fillStyle = 'rgba(120, 120, 120, 1)';
        ctx.fillText(cardInfo.Company, width / 2, height * 80 / 450, 280);
      }

      if (name) {
        // 活动名称
        ctx.setTextAlign('center');
        ctx.font = "18px sans-serif";
        ctx.fillStyle = 'rgba(251, 172, 38, 1)';
        ctx.fillText(name, width / 2, height * 150 / 450, 280);
      }

      // 绘制二维码
      if (codeSrc) {
        ctx.drawImage(codeSrc, width / 2 - width * 190 / 628, height * 172 / 450, width * 190 / 314, width * 190 / 314);
      }

      ctx.setTextAlign('center');
      ctx.font = "12px sans-serif";
      ctx.fillStyle = 'rgba(120, 120, 120, 1)';
      ctx.fillText('企动 · 玖玖客', width / 2, width * 397 / 314, 280);

    }).exec()

    setTimeout(function () {
      ctx.draw();
      wx.hideLoading();
    }, 1000)
  },
  savePost: function () {
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'myCanvas',
        success: function (res) {
          wx.hideLoading();
          var tempFilePath = res.tempFilePath;
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success(res) {
              wx.showModal({
                content: '图片已保存到相册，赶紧晒一下吧~',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#333',
                success: function (res) {
                  if (res.confirm) { }
                },
                fail: function (res) { }
              })
            },
            fail: function (res) {
              wx.showToast({
                title: '请删掉小程序再重新授权允许保存至相册',
                icon: 'none',
                duration: 2000,
                mask: true
              })
            }
          })
        }
      });
    }, 1000);
  },

  // 圆形图片
  circleImg: function (ctx, img, x, y, r) {
    ctx.save();
    ctx.beginPath();
    var d = 2 * r;
    var cx = x + r;
    var cy = y + r;
    ctx.arc(cx, cy, r, 0, 2 * Math.PI, false);
    ctx.clip();
    ctx.drawImage(img, x, y, d, d);
    ctx.restore();
  },

  painter: function (canasId, data) {
    var ctx = wx.createCanvasContext(canasId);
    var bg_url = data.bg_url;
    return new Promise((resolve, reject) => {
      wx.downloadFile({
        url: bg_url,
        success: res => {
          if (res.statusCode === 200) {
            ctx.beginPath();
            ctx.drawImage(res.tempFilePath, 0, 0, 300, 200); // 大图
            ctx.draw(true, () => {
              wx.canvasToTempFilePath({
                canvasId: canasId,
                success: res => {
                  resolve(res.tempFilePath)
                },
                fail: err => {
                  reject(err)
                }
              })
            })
          }
        }
      })
    })
  },

  //获取地理位置
  getMapLocaltion: function (e) {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        var markers = that.data.markers;
        markers[0].latitude = res.latitude;
        markers[0].longitude = res.longitude;
        that.setData({
          address: res.name,
          markers: markers,
          longitude: res.longitude,
          latitude: res.latitude
        })
      },
      fail: function () {
        wx.getSetting({
          success(res) {
            if (!res.authSetting['scope.userLocation']) {
              wx.authorize({
                scope: 'scope.userLocation',
                success(ress) {
                  wx.chooseLocation({
                    success: function (resag) {
                      var markers = that.data.markers;
                      markers[0].latitude = resag.latitude;
                      markers[0].longitude = resag.longitude;
                      that.setData({
                        address: resag.name,
                        markers: markers,
                        longitude: resag.longitude,
                        latitude: resag.latitude
                      })
                    },
                  })
                }
              })
            }
          }
        })
      }
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    let that = this;
    that.getShareImgData();
    if (that.data.tagindex == 1) {
      that.getFlyerSetting();
    }
    if (options.bgImg) {      
      let sendType = options.sendType;
      let gradeType = options.gradeType;
      let isNew = '';
      let isOld = '';
      if (sendType == 0) {
        isNew = true;
        isOld = true;
      }
      if (sendType == 1) {
        isNew = true;
        isOld = false;
      }
      if (sendType == 2) {
        isNew = false;
        isOld = true;
      }
      that.setData({
        flyerName: options.flyerName,
        sendType: sendType,
        isNew: isNew,
        isOld: isOld,
        flyerCount: options.flyerCount,
        gradeType: gradeType
      })
      that.data.flyerid = options.flyerid;
      that.data.template = options.bgImg;
      let showTemplateImg = utils.formatAvater(options.bgImg, 'https://static.711688.net.cn/upload/share/');
      that.setData({
        tagindex: 2,
        showTemplateImg: showTemplateImg,
        addFlyerDialog: !that.data.addFlyerDialog
      })
    }
    that.setData({
      platform: app.globalData.platform
    })
  },
  getFlyerInfoLoad: function (flyerid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Leaflet/GetGrade?id=' + flyerid,
      success: function (res) {
        if (res.data.Code == 0) {
          let sendType = res.data.Data.SendType;
          let isNew = '';
          let isOld = '';
          if (sendType == 0) {
            isNew = true;
            isOld = true;
          }
          if (sendType == 1) {
            isNew = true;
            isOld = false;
          }
          if (sendType == 2) {
            isNew = false;
            isOld = true;
          }
          that.setData({
            flyerName: res.data.Data.Name,
            sendType: sendType,
            isNew: isNew,
            isOld: isOld,
            flyerCount: res.data.Data.PackageCount
          })
        }
      },
    })
  },

  // 打开(关闭)活动
  openFlyer: function () {
    let state = this.data.state;
    if (state == 1) {
      state = 0;
    } else {
      state = 1;
    }
    this.setData({
      state: state
    })
    this.setFlyer();
  },

  // 传单发放距离位置设置
  getFlyerSetting: function () {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Leaflet/GetLeaflet?uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Data) {
          let info = res.data.Data;
          that.getRecharge(info.UnitPrice);
          that.data.unitPrice = info.UnitPrice;
          that.getDefaultAddress(1);
          that.setData({
            state: info.State,
            sendNumber: info.UserCount,
            address: info.Address,
            range: info.Km,
            createUid: info.Uid,
            latitude: info.Latitude,
            longitude: info.Longitude
          })
        } else {
          that.getRecharge(0);
          that.getDefaultAddress();
        }
      },
    })
  },
  getDefaultAddress: function (useByShare = 0) {
    let that = this;
    let userid = app.globalData.userInfo.Uid;
    wx.request({
      url: app.globalData.host + '/api/Staff/GetStaffIdByUid?Uid=' + userid,
      success: function (res) {
        let cardInfo = res.data.Data;
        if (cardInfo) {
          that.setData({
            merchantAddress: cardInfo.Address
          })
          if (useByShare != 1) {
            that.setData({
              address: cardInfo.Address,
              latitude: cardInfo.Latitude,
              longitude: cardInfo.Longitude
            })
          }
        }
      }
    })
  },

  // 获取余额
  getRecharge: function (unitprice) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Distributor/GetDistributorAndCreate?userId=' + app.globalData.userInfo.Uid + '&disId=0&agentId=0&storeId=' + app.globalData.storeId,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data) {
            let totalMoney = res.data.Data.RequestBalance + res.data.Data.AccountBalance;
            let predictCount = 0;
            if (unitprice > 0) {
              predictCount = parseInt(res.data.Data.AccountBalance / unitprice)
            }
            that.setData({
              balance: res.data.Data.AccountBalance,//余额
              predictCount: predictCount,//预计发放量
              totalMoney: parseFloat(totalMoney).toFixed(2),//已充值金额
            })
          }
        } else {
          that.checkWrite(res.data.Message);
        }
      },
    })
  },

  bindRange: function (e) {
    this.setData({
      range: e.detail.value
    })
  },

  bindAddress: function (e) {
    this.setData({
      address: e.detail.value
    })
  },

  // 保存活动
  setFlyer: function () {
    let that = this;
    let range = that.data.range;
    if (range == '') {
      range = 0;
    }
    if (that.data.address == '' && that.data.state == 1) {
      that.checkWrite('请选择投放坐标');
      return;
    }
    wx.request({
      url: app.globalData.host + '/api/Leaflet/SetLeaflet',
      data: {
        uid: app.globalData.userInfo.Uid,
        state: that.data.state,
        address: that.data.address,
        km: range,
        longitude: that.data.longitude,
        latitude: that.data.latitude
      },
      method: 'POST',
      success: function (res) {
        if (res.data.Code == 0) {
          wx.showToast({
            title: '保存成功',
            mask: true
          })
          that.getFlyerSetting();
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
          that.getFlyerSetting();
        }
      }
    })
  },
  // 添加传单活动
  addflyer: function () {
    let that = this;
    let flyerName = that.data.flyerName;
    if (flyerName == '') {
      that.checkWrite('请输入活动名称');
      return;
    }
    let flyerCount = that.data.flyerCount;
    if (flyerCount == '') {
      flyerCount = 0;
    }
    let sendType = that.data.sendType;
    let isNew = that.data.isNew;
    let isOld = that.data.isOld;
    if (!isNew && !isOld) {
      that.checkWrite('请选择发放人群');
      return;
    }
    if (isNew && isOld) {
      sendType = 0
    }
    if (isNew && !isOld) {
      sendType = 1
    }
    if (!isNew && isOld) {
      sendType = 2
    }
    wx.request({
      url: app.globalData.host + '/api/Leaflet/AddUpdateGrade',
      data: {
        id: that.data.flyerid,
        uid: app.globalData.userInfo.Uid,
        name: flyerName,
        sendType: sendType,
        packageCount: flyerCount,
        template: that.data.template,
        gradeType: that.data.gradeType
      },
      method: 'POST',
      success: function (res) {
        if (res.data.Code == 0) {
          that.checkWrite('保存成功');
          that.setData({
            gradeType: 1
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
        that.setData({
          addFlyerDialog: !that.data.addFlyerDialog
        })
        that.getFlyerList();
      }
    })
  },
  // 选择开启的传单活动
  selSendFlyer: function (e) {
    let that = this;
    let flyerid = e.currentTarget.dataset.flyerid;
    wx.request({
      url: app.globalData.host + '/api/Leaflet/SetState',
      data: {
        id: flyerid,
        uid: app.globalData.userInfo.Uid,
        state: 1
      },
      method: 'POST',
      success: function (res) {
        if (res.data.Code == 0) {
          wx.showToast({
            title: '设置成功',
            mask: true
          })
          that.setData({
            currentSendFlyerid: flyerid
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      },
    })
  },
  // 添加/修改传单参数设置
  changeIsnew: function () {
    this.setData({
      isNew: !this.data.isNew
    })
  },
  changeIsold: function () {
    this.setData({
      isOld: !this.data.isOld
    })
  },
  changeGradeType: function () {
    let gradeType = this.data.gradeType;
    if (gradeType == 0) {
      gradeType = 1;
    } else {
      gradeType = 0;
    }
    this.setData({
      gradeType: gradeType
    })
  },
  // 选择传单样式
  chooseBgImg: function () {
    let sendType = '';
    let isNew = this.data.isNew;
    let isOld = this.data.isOld;
    if (isNew && isOld) {
      sendType = 0
    }
    if (isNew && !isOld) {
      sendType = 1
    }
    if (!isNew && isOld) {
      sendType = 2
    }
    wx.navigateTo({
      url: '../chooseBgImg/index?flyerid=' + this.data.flyerid + '&sendType=' + sendType + '&flyerName=' + this.data.flyerName + '&flyerCount=' + this.data.flyerCount + '&gradeType=' + this.data.gradeType,
    })
  },
  // 传单列表
  getFlyerList: function () {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Leaflet/GetGradeList?uid=' + app.globalData.userInfo.Uid + '&page=' + that.data.currentPage,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data) {
            let flyerList = res.data.Data;
            if (that.data.currentPage != 1) {
              let preList = that.data.flyerList;
              flyerList = preList.concat(flyerList);
            }
            if (flyerList.length > 0) {
              for (let i = 0; i < flyerList.length; i++) {
                let count = 1;
                let gift = [];
                if (flyerList[i].State == 1) {
                  that.setData({
                    currentSendFlyerid: flyerList[i].Id
                  })
                }
                let cardItemList = flyerList[i].CardItemList;
                let couponTypeList = flyerList[i].CouponTypeList;
                if (cardItemList.length > 0) {
                  for (let j = 0; j < cardItemList.length; j++) {
                    let content = count + "、" + cardItemList[j].Name + "1张";
                    count++;
                    gift.push(content);
                  }
                }
                if (couponTypeList.length > 0) {
                  for (let k = 0; k < couponTypeList.length; k++) {
                    let content = '';
                    if (couponTypeList[k].money > 0) {
                      content = count + "、满" + couponTypeList[k].orderamountlower + "元减" + couponTypeList[k].money + "元代金券" + couponTypeList[k].Counts + "张";
                    } else if (couponTypeList[k].name != '') {
                      content = count + "、" + couponTypeList[k].name + "赠品券" + couponTypeList[k].Counts + "张";
                    }
                    else if (couponTypeList[k].extcode1 != '') {
                      content = count + "、买" + couponTypeList[k].extcode1 + "送" + couponTypeList[k].extcode2 + "赠品券" + couponTypeList[k].Counts + "张";
                    } else {
                      content = count + "、送" + couponTypeList[k].extcode2 + "赠品券" + couponTypeList[k].Counts + "张";
                    }
                    count++;
                    gift.push(content);
                  }
                }
                flyerList[i].gifts = gift;
              }
            }
            that.setData({
              flyerList: flyerList
            })
          }
        }
      },
    })
  },

  // 切换传单设置/数字传单
  changeTag: function (e) {
    let tagindex = e.currentTarget.dataset.tagindex;
    if (tagindex == 2) {
      this.getFlyerList();
    }
    if (tagindex == 1) {
      this.getFlyerSetting();
    }
    this.setData({
      tagindex: tagindex
    })
  },
  showRuler: function () {
    this.setData({
      showRuler: !this.data.showRuler
    })
  },
  // 新增传单活动弹窗
  addFlyerDialog: function () {
    this.setData({
      flyerid: 0,
      flyerName: '',
      flyerCount: '',
      isNew: true,
      isOld: true,
      template: '',
      showTemplateImg: '',
      addFlyerDialog: !this.data.addFlyerDialog
    })
  },
  // 编辑传单活动
  addFlyerDialogByid: function (e) {
    let that = this;
    let id = e.currentTarget.dataset.flyerid;
    wx.request({
      url: app.globalData.host + '/api/Leaflet/GetGrade?id=' + id,
      success: function (res) {
        if (res.data.Code == 0) {
          let template = res.data.Data.Template;
          let showTemplateImg = '';
          let isNew = '';
          let isOld = '';
          if (template) {
            showTemplateImg = utils.formatAvater(template, 'https://static.711688.net.cn/upload/share/');
          }
          if (res.data.Data.SendType == 0) {
            isNew = true;
            isOld = true
          }
          if (res.data.Data.SendType == 1) {
            isNew = true;
            isOld = false
          }
          if (res.data.Data.SendType == 2) {
            isNew = false;
            isOld = true
          }
          that.setData({
            flyerName: res.data.Data.Name,
            sendType: res.data.Data.SendType,
            template: template,
            showTemplateImg: showTemplateImg,
            flyerCount: res.data.Data.PackageCount,
            isNew: isNew,
            isOld: isOld,
            gradeType: res.data.Data.GradeType
          })
        }
      },
    })
    this.setData({
      flyerid: id,
      addFlyerDialog: !this.data.addFlyerDialog
    })
  },
  closeFlyerDialog: function () {
    this.setData({
      addFlyerDialog: !this.data.addFlyerDialog
    })
  },
  bindFlayerName: function (e) {
    this.setData({
      flyerName: e.detail.value
    })
  },
  addFlyerCoupon: function () {
    wx.navigateTo({
      url: '../flyerCardAndCoupon/index',
    })
  },
  toAddplyerPackge: function (e) {
    let flyerid = e.currentTarget.dataset.flyerid;
    wx.navigateTo({
      url: '../flyerCardAndCoupon/index?flyerid=' + flyerid,
    })
  },

  //监听用户滑动页面事件
  onPageScroll: function (e) {
    console.log(e);
    let top = parseInt(e.scrollTop) + 10;
    this.setData({
      top: top
    })
  },
  checkWrite: function (str) {
    wx.showToast({
      title: str,
      icon: 'none',
      mask: true
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.tagindex == 2) {
      this.getFlyerList();
    }
  },
  loadMore: function () {
    var that = this;
    if (that.data.loadingMoreHidden > 1 && that.data.currentPage < that.data.loadingMoreHidden) {
      var currPage = that.data.currentPage;
      that.setData({
        currentPage: currPage + 1
      })
      that.getFlyerList();
    } else {
      return
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.loadMore()
  },
  getShareImgData: function () {
    this.painter('share-canvas-id', {
      bg_url: 'https://static.711688.net.cn/upload/card/source/ua_2005131103020634897.jpg',
    })
      .then(data => {
        this.data.shareimgpath = data;
      })
      .catch(err => { })
  },

  toEditorInfo: function () {
    let cardid = wx.getStorageSync('cardId');
    wx.showModal({
      title: '提示',
      content: '商家地址未设置，无法帮人发传单',
      confirmText: '去设置',
      success: function (res) {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/weijieke/editorCard/index?staffid=' + cardid,
          })
        }
      }
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    console.log(e);
    let that = this;
    let cardid = wx.getStorageSync('cardId');
    return {
      imageUrl: that.data.shareimgpath,
      title: '您有免单礼包啦，免费领取',
      path: '/merchant/flyer/receiveLeafletCoupon/index?id=' + cardid + '&createUid=' + that.data.createUid,
      success: function (res) {
        wx.showModal({
          title: '提示',
          content: '转发成功',
          showCancel: false
        })
      }
    }
    // 测试测试
    // if (e.target.dataset.test == '单个分享') {
    //   return {
    //     imageUrl: that.data.shareimgpath,
    //     title: '单个礼包领取',
    //     path: '/merchant/flyer/oneStaffFlyer/index?flyerid=' + that.data.codeFlyerid + '&isTest=1',
    //     success: function (res) {
    //       wx.showModal({
    //         title: '提示',
    //         content: '转发成功',
    //         showCancel: false
    //       })
    //     }
    //   }
    // } else {      
    // }
  }
})